﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ReporterEngine.Methods
{
    public class IsMemberOf : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.Method && !string.IsNullOrEmpty(token.PathExp) && token.PathExp.ToLower() == "ismemberof";
        }

        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();

            foreach (var element in query.Elements)
            {
                var elementID = query._model.GetID(element).ToString();

                if (query._model.REFs.ContainsKey(elementID))
                foreach (var refEl in query._model.REFs[elementID])
                {
                    if (refEl.Parent.Name.LocalName == "members" && refEl.Parent.Parent.Parent.Name.LocalName != "modelScenarios")
                    {
                        var resParent = refEl.Parent.Parent;

                        result.Elements.Add(resParent);
                    }
                }
            }

            result.Elements = result.Elements.Distinct(new CIFModel.NodeComparer()).ToList();

            return result;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[]{new MethodDescription{Name = "isMemberOf"} };
        }
    }
}
